package com.ai.fupincore.control;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ai.frame.bean.InputObject;
import com.ai.frame.bean.OutputObject;
import com.ai.frame.logger.Logger;
import com.ai.frame.logger.LoggerFactory;
import com.ai.fupincore.dynamicDataSoure.DynamicDataSourceHolder;
import com.ai.fupincore.service.onest.IOnestService;
import com.ai.fupincore.util.Constants;
import com.ai.fupincore.util.Constants.FTP_CONFIG;
import com.ai.fupincore.util.DedicException;
import com.ai.fupincore.util.MySFtp;
import com.ai.fupincore.util.OnestUtil;
import com.ai.fupincore.util.PropertiesUtil;
import com.ai.fupincore.util.StringUtil;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.SftpATTRS;


public class OnestMain {
	private static final Logger LOGGER = LoggerFactory.getApplicationLog(OnestMain.class);
	private static String ENDPOINT = "ONEST_ENDPOINT";
	private static String UID = "UID";
	private static String DISPLAY_NAME = "DISPLAY_NAME";
	private static String ONEST_ENDPOINT_DISPLAY = "ONEST_ENDPOINT-DISPLAY";
	private static String BUCKET_NAME = "ONEST_bucketName";
	private static String ONEST_ENDPOINT_IN = "ONEST_ENDPOINT";//ONEST_ENDPOINT 内网地址
	private static String ONEST_ENDPOINT_OUT = "ONEST_ENDPOINT-DISPLAY";//ONEST_ENDPOINT 外网地址
	public static final ApplicationContext context = new ClassPathXmlApplicationContext("spring/spring-all.xml");
	public static IOnestService onestService = (IOnestService) context.getBean("onestService");
	
	public static void main(String[] args) throws Exception{
		DynamicDataSourceHolder.putDataSource("master");
		//getTbConfList();
//		if("1".equals(args[1])){
//			getTbConfList();  //正常数据 # AND f.pvtpsn_id NOT IN (SELECT rl_obj_id FROM t_pt_pvtpsn_onest_temp)
//		}else if("0".equals(args[1])){
//			getErrorData();   //错误数据
//		}else if("2".equals(args[1])){
//			getAddDataInfo(); //增量数据
//		}
		getAddDataInfo();
		LOGGER.info("**数据库全部表处理完成***","****END****");
	}
	/**
	 * 
	 * @Title  增量数据上传ONEST
	 * @Description:  TODO
	 * @param: @throws Exception
	 * @return 
	 * @throws
	 * @author zzx
	 * @Date 2018年10月18日
	 */
	public static void getAddDataInfo() throws Exception{
		InputObject inputObject = new InputObject(); 
		OutputObject outputObject = new OutputObject();
		Map<String,String> paraMap = new HashMap<>();
		paraMap.put("addFlag", "");
		inputObject.setParams(paraMap);
		onestService.queryTbConfList(inputObject, outputObject);
		List<Map<String,String>> list = outputObject.getBeans();
		if(list != null && !list.isEmpty()){
			for(Map<String,String> m : list){
				Map<String,String> map = new HashMap<String,String>();
				map.put("tableName", m.get("tableNm"));
				map.put("tableTmpName", m.get("tableNm").concat("_onest_temp"));
				map.put("params1", m.get("attrNm"));
				map.put("tbConfId", m.get("tbConfId"));
				map.put("tbIdNm", m.get("tbIdNm"));
				map.put("attrConfId", m.get("attrConfId"));
				map.put("validAttrForm", m.get("validAttrForm"));
				String addBrePicFlag =  m.get("addBrePicFlag");
				//查询表是否存在
				OutputObject exsOut = new OutputObject();
				onestService.checkTableIsExist(map,exsOut);
				String flag = exsOut.getBean().get("flag");
				if(!"1".equals(flag)){
					LOGGER.info("****",m.get("tableNm").concat("：表不存在****"));
					continue;
				}
				map.put("checkFlag", "1002");
				inputObject.setParams(map);
				//查询表里面的数据数量
				onestService.queryFileListCount(inputObject,outputObject);
				int total = Integer.parseInt(outputObject.getBean().get("total"));
				int limit = 800;
				int start = 0;
				do{					
					//查询表里面的数据
					map.put("limit", Integer.toString(limit));
					map.put("start", "0");
					OutputObject fileOutput = new OutputObject();
					onestService.queryFileList(inputObject,fileOutput);
					//List<Map<String,String>> fileList = fileOutput.getBeans();
					InputObject dInput = new InputObject();
					dInput.setParams(inputObject.getParams());
					//是否有缩略图需要处理
					if("1".equals(addBrePicFlag)){
						getTableDataAbbsList(dInput,fileOutput);//有缩略图
					}else{
						getTableDataList(dInput,fileOutput);//无
					}
					//onestService.queryFileListCount(inputObject,outputObject);
					//total = Integer.parseInt(outputObject.getBean().get("total"));
					start += limit;
				}while(start <= total);
				LOGGER.info(m.get("tableNm"),"：表数据处理完成****");
			}
		}
	}
	/**
	 * 
	 * @Title  异常数据处理
	 * @Description:  异常数据处理
	 * @param: 
	 * @return 
	 * @throws
	 * @author zzx
	 * @Date 2018年10月8日
	 */
	public static void getErrorData() throws Exception{
		InputObject inputObject = new InputObject(); 
		OutputObject outputObject = new OutputObject();
		//查询表里面的数据数量
		onestService.queryTbErrorConfListCount(inputObject,outputObject);
		int total = Integer.parseInt(outputObject.getBean().get("total"));
		int limit = 800;
		int start = 0;
		do{
			//查询表里面的数据
			inputObject.getParams().put("limit", Integer.toString(limit));
			inputObject.getParams().put("start", Integer.toString(start));
			OutputObject fileOutput = new OutputObject();
			onestService.queryTbErrorConfList(inputObject,fileOutput);
			List<Map<String,String>> list = outputObject.getBeans();
			//List<Map<String,String>> fileList = fileOutput.getBeans();
			InputObject dInput = new InputObject();
			dInput.setParams(inputObject.getParams());
			if(fileOutput.getBeans() != null && !fileOutput.getBeans().isEmpty()){
				getErrorDataList(dInput,fileOutput);
			}
			start += limit;
		}while(start <= total);
	}
	/**
	 * @Title  getTbConfList
	 * @Description:  读取需要ONEST处理的配置表列表
	 * 				循环需要处理的表，查询表里面的文件字段信息，读取出列表。
	 * @throws Exception
	 * @return 
	 * @author zzx
	 * @Date 2018年10月9日
	 */
	public static void getTbConfList() throws Exception{
		InputObject inputObject = new InputObject(); 
		OutputObject outputObject = new OutputObject();
		Map<String,String> paraMap = new HashMap<>();
		paraMap.put("addFlag", "1001");
		inputObject.setParams(paraMap);
		onestService.queryTbConfList(inputObject, outputObject);
		List<Map<String,String>> list = outputObject.getBeans();
		if(list != null && !list.isEmpty()){
			for(Map<String,String> m : list){
				Map<String,String> map = new HashMap<String,String>();
				map.put("tableName", m.get("tableNm"));
				//String str = m.get("attrNms");
				//String arrtNms[] = str.split(",");
				map.put("params1", m.get("attrNm"));
				map.put("tbConfId", m.get("tbConfId"));
				map.put("tbIdNm", m.get("tbIdNm"));
				map.put("attrConfId", m.get("attrConfId"));
				map.put("validAttrForm", m.get("validAttrForm"));
				String addBrePicFlag =  m.get("addBrePicFlag");
				String execState = m.get("execState");
				if("1".equals(execState)){
					//删除以前跑的错误数据
					onestService.delErrorConfList(m);
				}
				//查询表是否存在
				OutputObject exsOut = new OutputObject();
				onestService.checkTableIsExist(map,exsOut);
				String flag = exsOut.getBean().get("flag");
				if(!"1".equals(flag)){
					LOGGER.info("****",m.get("tableNm").concat("：表不存在****"));
					InputObject in = new InputObject();
					in.getParams().put("tbConfId", m.get("tbConfId"));
					in.getParams().put("execState", "2");
					onestService.updateConfInfo(in,outputObject);
					continue;
				}
				InputObject input = new InputObject();
				input.getParams().put("dataSource", input.getParams().get("dataSource"));
				input.getParams().put("tbConfId", m.get("tbConfId"));
				input.getParams().put("execState", "1");
				onestService.updateConfInfo(input,outputObject);
				map.put("checkFlag", "1001");
				inputObject.setParams(map);
				inputObject.setParams(map);
				//查询表里面的数据数量
				onestService.queryFileListCount(inputObject,outputObject);
				int total = Integer.parseInt(outputObject.getBean().get("total"));
				int limit = 800;
				int start = 0;
				do{
					//查询表里面的数据
					map.put("limit", Integer.toString(limit));
					map.put("start", Integer.toString(start));
					OutputObject fileOutput = new OutputObject();
					onestService.queryFileList(inputObject,fileOutput);
					//List<Map<String,String>> fileList = fileOutput.getBeans();
					InputObject dInput = new InputObject();
					dInput.setParams(inputObject.getParams());
					//是否有缩略图需要处理
					if("1".equals(addBrePicFlag)){
						getTableDataAbbsList(dInput,fileOutput);//有缩略图
					}else{
						getTableDataList(dInput,fileOutput);//无
					}
					start += limit;
				}while(start <= total);
				LOGGER.info("**正常数据执行完成**","*****end************");
				input.getParams().put("execState", "2");
				onestService.updateConfInfo(input,outputObject);
				LOGGER.info(m.get("tableNm"),"：表数据处理完成****");
			}
		}
	}
	/**
	 * 
	 * @Description:  二次上传异常数据
	 * @param: @param inputObject
	 * @param: @param outputObject
	 * @param: @throws Exception
	 * @return 
	 * @throws
	 * @author zzx
	 * @Date 2018年10月8日
	 */
	public static void getErrorDataList(InputObject inputObject, OutputObject outputObject) throws Exception{		
		Map<String,String> map = inputObject.getParams();
		List<Map<String,String>> list = outputObject.getBeans();
		String ftpIp = PropertiesUtil.getString(FTP_CONFIG.FTP_PREFIX_IN);
		List<Map<String,String>> insertList = new ArrayList<>();
		for(Map<String,String> m : list){
			String ftpFile = m.get("filePath");//m.get("FILE_PATH");
			String crtDate = "";
			if(StringUtil.isNotEmpty(ftpFile)){
				String sName = ftpFile.substring(ftpFile.lastIndexOf("/")+1);
				crtDate = getYearMonth(sName);
				if(ftpFile.length()>9 && PropertiesUtil.getString(BUCKET_NAME).equals(ftpFile.substring(0,9))){//已经是ONEST地址
					continue;
				}
				if("/".equals(ftpFile.substring(0,1))){
					ftpFile = ftpIp.concat(ftpFile.substring(1));
				}else{
					ftpFile = ftpIp.concat(ftpFile);
				}
			}else{
				continue;
			}
			String rtnUrl = getFtpFile(ftpFile,crtDate);
			if(StringUtil.isEmpty(rtnUrl)){
				continue;
			}
			//插入临时表
			Map<String,String> DataMap = new HashMap<>();
			DataMap.put("onestFilePath", rtnUrl);
			DataMap.put("rlObjId", m.get(map.get("tbIdNm")));
			DataMap.put("ftpFilePath",m.get("filePath"));
			DataMap.put("params1",m.get("attrNm"));
			DataMap.put("dtlId",m.get("dtlId"));
			DataMap.put("tableName",map.get("tableName"));
			String tableNameTemp = map.get("tableName");
			if(StringUtil.isEmpty(tableNameTemp)){
				LOGGER.info("**获取表名出错***","****表明获取失败****");
				continue;
			}
			tableNameTemp = tableNameTemp.concat("_onest_temp");
			DataMap.put("tableTmpName",tableNameTemp);
			map.put("tableNameTemp",tableNameTemp);
			insertList.add(DataMap);
			if(insertList.size()%100 ==0){
				String str = com.alibaba.fastjson.JSONObject.toJSONString(insertList);
				map.put("fileList",str);
				InputObject saveInput = new InputObject();
				saveInput.setParams(map);
				//插入临时表
				onestService.insertOnestDataInfo(saveInput);
				insertList.clear();
			}
		}
		if(insertList != null && !insertList.isEmpty()){
			String str = com.alibaba.fastjson.JSONObject.toJSONString(insertList);
			map.put("fileList",str);
			InputObject saveInput = new InputObject();
			saveInput.setParams(map);
			//插入临时表
			onestService.insertOnestDataInfo(saveInput);
			insertList.clear();
		}
		//updateTableData(inputObject);
		//删除异常数据
		OutputObject errOut = new OutputObject();
		onestService.delErrorDateInfo(inputObject,errOut);
	}
	/**
	 * @Title  getTableDataList
	 * @Description:  把数据库的数据列表逐条上传到ONTEST,并把上传成功后的 ONEST附件地址更新到原表。
	 * @throws Exception
	 * @return 
	 * @author zzx
	 * @Date 2018年10月9日
	 */
	public static void getTableDataList(InputObject inputObject, OutputObject outputObject) throws Exception{		
		Map<String,String> map = inputObject.getParams();
		List<Map<String,String>> list = outputObject.getBeans();
		String ftpIp = PropertiesUtil.getString(FTP_CONFIG.FTP_PREFIX_IN);
		List<Map<String,String>> insertList = new ArrayList<>();
		for(Map<String,String> m : list){
			String params = map.get("params1");
			String ftpFile = m.get(params);//m.get("FILE_PATH");
			String crtDate = "";
			if(StringUtil.isNotEmpty(ftpFile)){
				String sName = ftpFile.substring(ftpFile.lastIndexOf("/")+1);
				crtDate = getYearMonth(sName);
				if(ftpFile.length()>9 && PropertiesUtil.getString(BUCKET_NAME).equals(ftpFile.substring(0,9))){//已经是ONEST地址
					continue;
				}
				if("/".equals(ftpFile.substring(0,1))){
					ftpFile = ftpIp.concat(ftpFile.substring(1));
				}else{
					ftpFile = ftpIp.concat(ftpFile);
				}
			}else{
				continue;
			}
			String rtnUrl = getFtpFile(ftpFile,crtDate);//原图
			//String rtnUrl = picAbbrev(ftpFile,crtDate);//缩略图处理
			if(StringUtil.isEmpty(rtnUrl)){
				Map<String,String> erMap = new HashMap<>();
				erMap.put("tbConfId", map.get("tbConfId"));
				erMap.put("attrConfId", map.get("attrConfId"));
				erMap.put("filePath", m.get(params));
				erMap.put("errorState", "2");
				erMap.put("crtUserId", "U100000000001X");
				erMap.put("crtAppSysId", "1300");
				erMap.put("validStsCd", "1");
				inputObject.setParams(erMap);
				onestService.saveErrorDtl(inputObject,outputObject);
				continue;
			}
			Map<String,String> DataMap = new HashMap<>();
			DataMap.put("onestFilePath", rtnUrl);
			DataMap.put("rlObjId", m.get(map.get("tbIdNm")));
			DataMap.put("ftpFilePath",m.get(params));
			DataMap.put("tableName",map.get("tableName"));
			String tableNameTemp = map.get("tableName");
			if(StringUtil.isEmpty(tableNameTemp)){
				LOGGER.info("**获取表名出错***","****表明获取失败****");
				continue;
			}
			tableNameTemp = tableNameTemp.concat("_onest_temp");
			DataMap.put("tableTmpName",tableNameTemp);
			map.put("tableNameTemp",tableNameTemp);
			insertList.add(DataMap);
			if(insertList.size()%100 ==0){
				String str = com.alibaba.fastjson.JSONObject.toJSONString(insertList);
				map.put("fileList",str);
				InputObject saveInput = new InputObject();
				saveInput.setParams(map);
				//插入临时表
				onestService.insertOnestDataInfo(saveInput);
				insertList.clear();
			}
			//inputObject.setParams(map);
			//插入临时表
			//onestService.insertOnestDataInfo(inputObject);
			//updateTableData(inputObject);
		}
		if(insertList != null && !insertList.isEmpty()){
			String str = com.alibaba.fastjson.JSONObject.toJSONString(insertList);
			map.put("fileList",str);
			InputObject saveInput = new InputObject();
			saveInput.setParams(map);
			//插入临时表
			onestService.insertOnestDataInfo(saveInput);
			insertList.clear();
		}
	}
	/**
	 * @Title  getTableDataAbbsList
	 * @Description:  有缩略图处理：把数据库的数据列表逐条上传到ONTEST,并把上传成功后的 ONEST附件地址更新到原表。
	 * @throws Exception
	 * @return 
	 * @author zzx
	 * @Date 2018年10月9日
	 */
	public static void getTableDataAbbsList(InputObject inputObject, OutputObject outputObject) throws Exception{		
		Map<String,String> map = inputObject.getParams();
		List<Map<String,String>> list = outputObject.getBeans();
		String ftpIp = PropertiesUtil.getString(FTP_CONFIG.FTP_PREFIX_IN);
		List<Map<String,String>> insertList = new ArrayList<>();
		for(Map<String,String> m : list){
			String params = map.get("params1");
			String ftpFile = m.get(params);//m.get("FILE_PATH");
			String crtDate = "";
			if(StringUtil.isNotEmpty(ftpFile)){
				String sName = ftpFile.substring(ftpFile.lastIndexOf("/")+1);
				crtDate = getYearMonth(sName);
				if(ftpFile.length()>9 && PropertiesUtil.getString(BUCKET_NAME).equals(ftpFile.substring(0,9))){//已经是ONEST地址
					continue;
				}
				if("/".equals(ftpFile.substring(0,1))){
					ftpFile = ftpIp.concat(ftpFile.substring(1));
				}else{
					ftpFile = ftpIp.concat(ftpFile);
				}
			}else{
				continue;
			}
			//String rtnUrl = getFtpFile(ftpFile,crtDate);//原图
			String rtnUrl = picAbbrev(ftpFile,crtDate);//缩略图处理
			if(StringUtil.isEmpty(rtnUrl)){
				Map<String,String> erMap = new HashMap<>();
				erMap.put("tbConfId", map.get("tbConfId"));
				erMap.put("attrConfId", map.get("attrConfId"));
				erMap.put("filePath", m.get(params));
				erMap.put("errorState", "2");
				erMap.put("crtUserId", "U100000000001X");
				erMap.put("crtAppSysId", "1300");
				erMap.put("validStsCd", "1");
				inputObject.setParams(erMap);
				onestService.saveErrorDtl(inputObject,outputObject);
				continue;
			}
			Map<String,String> DataMap = new HashMap<>();
			DataMap.put("onestFilePath", rtnUrl);
			DataMap.put("rlObjId", m.get(map.get("tbIdNm")));
			DataMap.put("ftpFilePath",m.get(params));
			DataMap.put("tableName",map.get("tableName"));
			String tableNameTemp = map.get("tableName");
			if(StringUtil.isEmpty(tableNameTemp)){
				LOGGER.info("**获取表名出错***","****表明获取失败****");
				continue;
			}
			tableNameTemp = tableNameTemp.concat("_onest_temp");
			DataMap.put("tableTmpName",tableNameTemp);
			map.put("tableNameTemp",tableNameTemp);
			insertList.add(DataMap);
			if(insertList.size()%100 ==0){
				String str = com.alibaba.fastjson.JSONObject.toJSONString(insertList);
				map.put("fileList",str);
				InputObject saveInput = new InputObject();
				saveInput.setParams(map);
				//插入临时表
				onestService.insertOnestDataInfo(saveInput);
				insertList.clear();
			}
			//inputObject.setParams(map);
			//插入临时表
			//onestService.insertOnestDataInfo(inputObject);
			//updateTableData(inputObject);
		}
		if(insertList != null && !insertList.isEmpty()){
			String str = com.alibaba.fastjson.JSONObject.toJSONString(insertList);
			map.put("fileList",str);
			InputObject saveInput = new InputObject();
			saveInput.setParams(map);
			//插入临时表
			onestService.insertOnestDataInfo(saveInput);
			insertList.clear();
		}
	}
	public static String getYearMonth(String str){
		String rtnDate = "999999";
		if(StringUtil.isNotEmpty(str) && str.length()>6){
			String ymStr = str.substring(0,6);
			String regx = "([2][0][1]\\d{1})(([0][1-9])|([1][0-2]))";
			if(ymStr.matches(regx)){
				rtnDate = ymStr;
			}
		}
		return rtnDate;
	}
	/**
	 * 
	 * @Title updateTableData 
	 * @Description:  更新表数据的附件地址。
	 * @param: @param inputObject
	 * @param: @throws DedicException
	 * @return 
	 * @throws
	 * @author zzx
	 * @Date 2018年10月9日
	 */
	public static void updateTableData(InputObject inputObject) throws DedicException{
		OutputObject outputObject = new OutputObject();	
		onestService.updateTableData(inputObject,outputObject);
	}
	/**
	 * @Title  getFtpFile
	 * @Description:  解析FTP上的图片地址，
	 * @param: @param ftpUrl
	 * @param: @param crtDate
	 * @param: @return
	 * @param: @throws Exception
	 * @return 
	 * @throws
	 * @author zzx
	 * @Date 2018年10月9日
	 */
	public static String getFtpFile(String ftpUrl,String crtDate) throws Exception{
		URL url= new URL(ftpUrl);
		URLConnection conn = url.openConnection();
		String message = conn.getHeaderField(0);
		if(StringUtil.isEmpty(message)){
			System.err.println("***地址错误********");
			return "";
		}
        if (message.startsWith("HTTP/1.1 404")) {
            LOGGER.info("**404文件地址解析错误***","****文件不存在或者循环无法解析****");
            return "";
        }
        if (message.startsWith("HTTP/1.1 400")) {
            LOGGER.info("**400文件地址解析错误***","****文件不存在或者循环无法解析****");
            return "";
        }
        if (!message.startsWith("HTTP/1.1 200")) {
            LOGGER.info("**非200文件地址解析错误***","****文件不存在或者循环无法解析****");
            return "";
        }
		String fileName = url.getFile();
		InputStream is = conn.getInputStream();
		String rtnUrl = uploadFile(fileName,crtDate,is);//FTP 文件上传
		return rtnUrl;
	}
	/**
	 * @Title  
	 * @Description:  本地测试URL路径解析为文件流。输出到本地文件。
	 * @param: @param ftpUrl
	 * @param: @param crtDate
	 * @param: @throws IOException
	 * @return 
	 * @throws
	 * @author zzx
	 * @Date 2018年10月9日
	 */
	public static void localSaveFile(String ftpUrl,String crtDate) throws IOException{
		URL url= new URL(ftpUrl);
		URLConnection conn = url.openConnection();
		String message = conn.getHeaderField(0);
        if (message.startsWith("HTTP/1.1 404")) {
            System.out.println("不存在");
        }
		String fileName = url.getFile().substring(url.getFile().lastIndexOf("/")+1);
		InputStream is = conn.getInputStream();
		File file = new File("d://aaa/"+fileName);
		/*if(!file.exists()){  
		    file.mkdirs();  
		} */
		FileOutputStream fos = new FileOutputStream(file);
		
		byte datas[] = new byte[1024*8];
        //创建长度
        int len = 0;
        //循环读取数据
        while((len = is.read(datas))!=-1){
            fos.write(datas,0,len);
        }
        //3.释放资源
        is.close();
        fos.close();
        //System.err.println("****文件保存到本地成功:d:/aaa/");
	}
	/**
	 * @Title  
	 * @Description:  文件上传到FTP服务器。
	 * @param: @param file
	 * @return 
	 * @throws
	 * @author zzx
	 * @Date 2018年10月9日
	 */
	public static void uploadFtpPic(File file){		
		MySFtp sf = new MySFtp();
		ChannelSftp sftp = null;
		try {
			//File file = new File("D:/aaa/1.jpg");
	    	String fileName = "1.jpg";
	    	FileInputStream fis = new FileInputStream(file);    
			String fileContent = "";//getInputObject().getParams().get("filecontent");
			if (fileName != null && fileContent != null) {

				SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
				String dateStr = df.format(new Date());

				fileName = fileName.substring(0, fileName.lastIndexOf("."))+ dateStr + fileName.substring(fileName.lastIndexOf("."));
				//http://172.22.225.70:20500/fupinnew/pic/120180927174451449.jpg
				// ftp服务地址
            	String hostIp = PropertiesUtil.getString(FTP_CONFIG.FTP_HOST_IP);
            	// ftp端口
            	int port = PropertiesUtil.getInt(FTP_CONFIG.FTP_HOST_PORT);
            	// ftp用户账号
            	String userName = PropertiesUtil.getString(FTP_CONFIG.FTP_HOST_USERNAME);
            	// ftp用户密码
            	String userPwd = PropertiesUtil.getString(FTP_CONFIG.FTP_HOST_USERPD);
            	
            	String remotePath = PropertiesUtil.getString(FTP_CONFIG.FTP_UPLOAD_PATH_PIC);
            	String ftpId = PropertiesUtil.getString(FTP_CONFIG.FTP_PREFIX_OUT);
            	sftp = sf.connect(hostIp, port, userName, userPwd);
            	sftp.cd(remotePath);
            	sf.upload(fileName, fis, sftp);
            	String ftpUrlApp = PropertiesUtil.getString(Constants.FTP_CONFIG.FTP_UPLOAD_PATH_PIC_NGINX);
            	System.err.println("**文件名："+fileName);
            	System.err.println("**FTP 地址："+ftpUrlApp);
            	String picUrl = ftpUrlApp.concat("/").concat(fileName);
            	System.err.println("**picUrl：*****"+(ftpId+picUrl));
			}			
		} catch (Exception exception) {
			System.err.println("系统异常");
		} finally {
			sf.disconnect(sftp);
		}
	}
	/**
	 * 
	 * @Title uploadFile
	 * @Description: 测试 ONEST 文件上传
	 * @param: @throws Exception
	 * @return void
	 * @throws FileNotFoundException 
	 * @throws
	 * @author zzx
	 * @Date 2018年9月27日   下午5:22:42
	 */
	public static String uploadFile(String fileName ,String crtDate,InputStream fis) throws FileNotFoundException{
		//File file = new File("D:/aaa/22.jpg");
		
		String strName = fileName.substring(fileName.lastIndexOf("/")+1);
    	//String strPath = fileName.substring(0,fileName.lastIndexOf("/"));
    	//FileInputStream fis = new FileInputStream(file);    	
    	Map<String,String> onestMap = new HashMap<String,String>();
    	onestMap.put("ONEST.ENDPOINT", PropertiesUtil.getString(ENDPOINT));
    	onestMap.put("ONEST.UID", PropertiesUtil.getString(UID));
    	onestMap.put("ONEST.DISPLAY-NAME", PropertiesUtil.getString(DISPLAY_NAME));
    	onestMap.put("ONEST.BUCKET_NAME", PropertiesUtil.getString(BUCKET_NAME));
    	StringBuilder strB = new StringBuilder();
    	strB.append(PropertiesUtil.getString(BUCKET_NAME)).append("/").append(crtDate);
    	onestMap.put("bucketName",strB.toString());
        String url;
		try {
			 url = OnestUtil.uploadAndGetPrivateUrlForH5(onestMap, strName,fis);
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.info("**文件上传ONEST***","****上传失败返回空路径****");
			url = "";
		}
        return url;
	}
	/**
	 * 
	 * @Title ftpFileTime
	 * @Description: 获取文件创建时间
	 * @param: @param remotePath
	 * @param: @return
	 * @return String
	 * @throws
	 * @author zzx
	 * @Date 2018年9月28日   下午3:03:48
	 */
	public static String ftpFileTime(String remotePath){
		MySFtp sf = new MySFtp();
		ChannelSftp sftp = null;
		String rtnDate = "";
		try {				
			// ftp服务地址
        	String hostIp = PropertiesUtil.getString(FTP_CONFIG.FTP_HOST_IP);
        	// ftp端口
        	int port = PropertiesUtil.getInt(FTP_CONFIG.FTP_HOST_PORT);
        	// ftp用户账号
        	String userName = PropertiesUtil.getString(FTP_CONFIG.FTP_HOST_USERNAME);
        	// ftp用户密码
        	String userPwd = PropertiesUtil.getString(FTP_CONFIG.FTP_HOST_USERPD);
        	String ftpId = PropertiesUtil.getString(FTP_CONFIG.FTP_PREFIX_OUT);
        	sftp = sf.connect(hostIp, port, userName, userPwd);
        	if("/".equals(remotePath.substring(0,1))){
        		remotePath = remotePath.substring(1);
        	}
        	remotePath = "apps-share/nginx-html/"+remotePath;
        	///home/zyzx/apps-shareinx-html/fupinnew/file

        	Vector files = sftp.ls(remotePath);
    		ChannelSftp.LsEntry strFile = (LsEntry) files.get(0);
    		SftpATTRS attrs = strFile.getAttrs();
    		//long aTime = attrs.getATime()*1000l;//最后一次访问时间
    		long mTime = attrs.getMTime()*1000l;//文件修改时间
    		SimpleDateFormat df=new SimpleDateFormat("yyyyMM");
    		//String rtnDate1 = df.format(mTime);
    		rtnDate = df.format(mTime);
		} catch (Exception exception) {
			LOGGER.info("**读取FTP文件目录结构***","****读取失败，文件或文件夹不存在****");
			Date data = new Date();
    		SimpleDateFormat df=new SimpleDateFormat("yyyyMM");
    		rtnDate = df.format(data);
		} finally {
			sf.disconnect(sftp);
		}
		return rtnDate;
	}
	/**
	 * @Title  
	 * @Description: 图片缩略图处理
	 * @param: 
	 * @return 
	 * @throws Exception 
	 * @throws
	 * @author zzx
	 * @Date 2018年10月10日
	 */
	public static String picAbbrev(String ftpFile ,String crtDate) throws Exception{
		String url = getFtpFile(ftpFile,crtDate);		
		if(StringUtil.isEmpty(url)){
			return url;
		}
		String f220x150 = new StringBuffer(ftpFile).append("_220x150.jpg").toString();
		String f690x470 = new StringBuffer(ftpFile).append("_690x470.jpg").toString();
		String f1586x1080 = new StringBuffer(ftpFile).append("_1586x1080.jpg").toString();		
		String imgName220x150 = getFtpFile(f220x150,crtDate);
		String imgName690x470 = getFtpFile(f690x470,crtDate);
		String imgName1586x1080 = getFtpFile(f1586x1080,crtDate);
		StringBuffer strB = new StringBuffer();
		strB.append(url);
		if(StringUtil.isNotEmpty(imgName220x150)){
			strB.append(",").append(imgName220x150);
			if(StringUtil.isNotEmpty(imgName690x470)){
				strB.append(",").append(imgName690x470);
				if(StringUtil.isNotEmpty(imgName1586x1080)){
					strB.append(",").append(imgName1586x1080);
				}
			}
		}
		return strB.toString();
	}
	/**
	 * 压缩图片到指定大小
	 * @param input
	 * @param temp
	 * @param w
	 * @param h
	 * @throws DedicException 
	 * @throws IOException 
	 */
	private static void scale(InputStream input, ByteArrayOutputStream temp, int w, int h) throws DedicException {
       try {
			
    	   BufferedImage srcImage = ImageIO.read(input); //读入文件 
	        int width = srcImage.getWidth(); // 得到源图宽  
	        int height = srcImage.getHeight(); // 得到源图长
	        
	        // 为等比缩放计算输出的图片宽度及高度
			double rate1 = ((double) width) / (double) w;
			double rate2 = ((double) height) / (double) h;
			// 根据缩放比率大的进行缩放控制
			double rate = rate1 > rate2 ? rate1 : rate2;
			int wih ;
			int heh ;
			if(rate > 1){
				wih = (int) (((double) width) / rate);
				heh = (int) (((double) height) / rate);
			}else{
				wih = width;
				heh = height;
			}
			Image image = srcImage.getScaledInstance(wih, heh, Image.SCALE_SMOOTH);
			BufferedImage target = new BufferedImage(wih, heh, BufferedImage.TYPE_INT_RGB);
			Graphics g = target.getGraphics();
			g.drawImage(image, 0, 0, null); // 绘制缩小后的图
			g.dispose();
			ImageIO.write(target, "JPEG", temp);// 输出到文件流
       } catch (IOException e) {
       	LOGGER.error("", "",e);	
       }
    }
}
